<template>
  <div class="notice-list-view">
    <div class="notice-header">
      <div class="time-column">公告发布<br />时间</div>
      <div class="content-column">公告发布内容</div>
      <div class="operation-column">操作</div>
    </div>

    <div v-if="loading" class="loading-container">
      <div v-loading="true" class="loading-placeholder"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="noticeList.length === 0" class="empty-container">
      <p>暂无公告信息</p>
    </div>

    <div v-else class="notice-list">
      <div
        v-for="(notice, index) in noticeList"
        :key="index"
        class="notice-item"
      >
        <div class="time-column">{{ notice.publishTime }}</div>
        <div class="content-column ellipsis">{{ notice.content }}</div>
        <div class="operation-column">
          <el-button link type="primary" @click="viewNoticeDetail(notice)">
            查看详情
          </el-button>
        </div>
      </div>
    </div>

    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="公告详情"
      width="600px"
      destroy-on-close
    >
      <div class="notice-detail">
        <div class="time-header">
          <span class="label">发布时间：</span>
          <span class="value">{{
            currentNotice.publishTime || '未知时间'
          }}</span>
        </div>
        <div class="content-container">
          <div class="content">{{ currentNotice.content }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getNoticeList } from '../../apis/notice'

const noticeList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentNotice = ref({})

// 将时间戳或日期字符串格式化为可读格式
const formatDateTime = (dateStr) => {
  if (!dateStr) return '未知时间'
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return '未知时间'

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    const second = String(date.getSeconds()).padStart(2, '0')

    return `${year}/${month}/${day} ${hour}:${minute}:${second}`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return '未知时间'
  }
}

// 获取公告列表
const fetchNoticeList = async () => {
  loading.value = true
  try {
    const res = await getNoticeList()

    // 确保响应数据格式正确并包含必要字段
    if (res && res.data && Array.isArray(res.data)) {
      noticeList.value = res.data.map((item) => ({
        publishTime: formatDateTime(item.publish_time),
        content: item.content || '无内容',
      }))
    } else {
      noticeList.value = []
      console.error('返回的公告数据格式不正确:', res)
    }

    // 如果没有数据，显示暂无公告
    if (noticeList.value.length === 0) {
      ElMessage.warning('暂无公告')
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)

    // 对于404错误，给出更友好的提示
    if (error.response && error.response.status === 404) {
      ElMessage.info('公告服务暂未配置，请联系管理员')
      // 添加一些测试数据以便UI正常显示
      noticeList.value = [
        {
          publishTime: formatDateTime(new Date()),
          content: '公告服务测试数据 - 这是一条测试公告内容',
        },
        {
          publishTime: formatDateTime(new Date(Date.now() - 86400000)), // 昨天
          content: '公告服务测试数据 - 欢迎使用智慧交通系统',
        },
      ]
    } else {
      ElMessage.error('获取公告列表失败: ' + (error.message || '未知错误'))

      // 添加一些模拟数据用于UI显示
      noticeList.value = [
        {
          publishTime: '未知时间',
          content: '获取公告失败，显示测试数据',
        },
      ]
    }
  } finally {
    loading.value = false
  }
}

// 查看公告详情
const viewNoticeDetail = (notice) => {
  currentNotice.value = notice
  dialogVisible.value = true
}

onMounted(() => {
  fetchNoticeList()
})

// 暴露方法给父组件
defineExpose({
  fetchNoticeList,
})
</script>

<style lang="scss" scoped>
.notice-list-view {
  padding: 0;
  width: 100%;
  background-color: #fff;

  .notice-header {
    display: flex;
    background-color: #f5f7fa;
    font-weight: bold;
    border-bottom: 1px solid #ebeef5;
    text-align: center;

    div {
      padding: 10px;
    }
  }

  .notice-list {
    .notice-item {
      display: flex;
      border-bottom: 1px solid #ebeef5;

      &:hover {
        background-color: #f5f7fa;
      }

      div {
        padding: 15px 10px;
      }
    }
  }

  .time-column {
    flex: 1;
    text-align: center;
  }

  .content-column {
    flex: 3;

    &.ellipsis {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .operation-column {
    flex: 1;
    text-align: center;
  }

  .loading-container,
  .empty-container {
    padding: 30px;
    text-align: center;
    color: #909399;

    .loading-placeholder {
      width: 100%;
      height: 100px;
    }
  }

  .notice-detail {
    padding: 20px;

    .time-header {
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;

      .label {
        font-weight: bold;
        color: #606266;
      }

      .value {
        color: #303133;
      }
    }

    .content-container {
      min-height: 150px;

      .content {
        white-space: pre-wrap;
        line-height: 1.8;
        color: #303133;
        font-size: 14px;
      }
    }
  }
}
</style>
